﻿using Core.Tools.IOC;
using Hardware.Reactor.Base;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UI.Application.Initialize.Models;
using UI.Application.Share.Config;
using UI.Application.Share.Event;
using UI.Application.Share.Initialize;

namespace UI.Application.Initialize.Services
{
    /// <summary>
    /// 硬件声明周期管理器
    /// </summary>
    [ExposedService(Lifttime.Singleton,typeof(IHardwareManager))]
    public class HardwareManager: IHardwareManager
    {
        private IEventAggregator EventAggregator {  get;  }
        private ITemp1Reader Temp1Reader { get; }
        private ITemp2Reader Temp2Reader { get; }

        /// <summary>
        /// 表示硬件初始化完成
        /// </summary>
        public bool Initialized { get; set; }//所有的硬件都加载成功
        public ISystemConfigProvider SystemConfigProvider { get; private set; }
        public HardwareManager(IEventAggregator eventAggregator,
            ISystemConfigProvider systemConfigProvider,
            ITemp1Reader temp1Reader, 
            ITemp2Reader temp2Reader)
        {
            SystemConfigProvider= systemConfigProvider;
            EventAggregator = eventAggregator;
            Temp1Reader = temp1Reader;
            Temp2Reader = temp2Reader;
        }

        public async Task<HardwareInitializeResult>InitAsync()
        {
            if (Initialized) throw new Exception("重复初始化硬件");
            //to do 将来去真正初始化 硬件模块
            Task<bool> task_Temp1Reader = Task.Run(() => Temp1Reader.Init(SystemConfigProvider));//里氏替换原则，SystemConfigProvider和ReactorConfigProvider是子父关系
            Task<bool> task_Temp2Reader = Task.Run(() => Temp2Reader.Init(SystemConfigProvider));//里氏替换原则，SystemConfigProvider和ReactorConfigProvider是子父关系
            var list = await Task.WhenAll(task_Temp1Reader,task_Temp2Reader);//当两个线程全部结束
            bool result = list.All(p => p);
            if (!result)
            {
                string msg = "硬件初始化失败:";
                if (!task_Temp1Reader.Result)
                {
                    msg += "1号反应釜温度模块|";
                }
                if (!task_Temp2Reader.Result)
                {
                    msg += "2号反应釜温度模块|";
                }

                return new HardwareInitializeResult//这里return就不会执行下面这一块了
                {
                    Message = msg,
                    Success = false,
                };
            }

            //await Task.Delay(750);//这里是演示的

            Initialized = true;
            EventAggregator.GetEvent<InitialiezdSuccessEvent>().Publish();//硬件初始化完成的事件发布，这里也可以用PrismProvider
            
            return new HardwareInitializeResult() { Message="硬件初始化完成",Success=true};
        }
    }
}
